import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types/user'
import { UserRole } from '@/types/user'
import { login as apiLogin, register as apiRegister, logout as apiLogout } from '@/api/auth'
import { getCurrentUser, updateUserProfile } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref<boolean>(false)
  const error = ref<string | null>(null)

  // Getters
  const isAuthenticated = computed(() => {
    console.log('isAuthenticated check:', {
      hasToken: !!token.value,
      hasUser: !!user.value,
      result: !!token.value && !!user.value
    })
    return !!token.value && !!user.value
  })
  const isAdmin = computed(() => {
    console.log('isAdmin check:', {
      userRole: user.value?.role,
      result: user.value?.role === UserRole.ADMIN || false
    })
    return user.value?.role === UserRole.ADMIN || false
  })

  // Actions
  const login = async (credentials: { username: string; password: string }) => {
    try {
      isLoading.value = true
      error.value = null
      const result = await apiLogin(credentials)
      token.value = result.token
      user.value = {
        ...result.user,
        role: result.user.roles?.[0] || 'user',
        status: 'active',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      localStorage.setItem('token', result.token)
      localStorage.setItem('user', JSON.stringify(result.user))
      // 同时设置userId和user_id以便其他组件使用
      localStorage.setItem('userId', result.user.id.toString())
      localStorage.setItem('user_id', result.user.id.toString())
      return result
    } catch (err: any) {
      error.value = err.message || '登录失败，请检查您的用户名和密码'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const register = async (userData: { username: string; password: string; email: string }) => {
    try {
      isLoading.value = true
      error.value = null
      const response = await apiRegister(userData)
      return response
    } catch (err: any) {
      error.value = err.message || '注册失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const fetchUserInfo = async () => {
    try {
      isLoading.value = true
      const profile = await getCurrentUser()
      // 将UserProfile合并到当前user对象中
      if (user.value) {
        Object.assign(user.value, profile)
      }
    } catch (err: any) {
      console.error('获取用户信息失败:', err)
      // 不要自动登出，让用户资料页面处理错误
      error.value = err.message || '获取用户信息失败'
    } finally {
      isLoading.value = false
    }
  }

  const updateInfo = async (userData: Partial<User>) => {
    try {
      isLoading.value = true
      const profile = await updateUserProfile(userData as any)
      if (user.value) {
        Object.assign(user.value, profile)
      }
      return profile
    } catch (err: any) {
      error.value = err.message || '更新失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const logout = () => {
    try {
      apiLogout()
    } catch (err) {
      console.error('登出失败:', err)
    } finally {
      user.value = null
      token.value = null
      error.value = null
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('userId')
      localStorage.removeItem('user_id')
    }
  }

  const clearError = () => {
    error.value = null
  }

  const setUser = (userData: User) => {
    user.value = userData
    localStorage.setItem('user', JSON.stringify(userData))
    // 同时设置userId和user_id
    localStorage.setItem('userId', userData.id.toString())
    localStorage.setItem('user_id', userData.id.toString())
  }

  const setToken = (tokenValue: string) => {
    token.value = tokenValue
    localStorage.setItem('token', tokenValue)
  }

  // 创建默认的模拟用户数据（已移除，不再使用）
  // const createMockUser = (): User => {
  //   const now = new Date().toISOString()
  //   return {
  //     id: '1',
  //     username: '游客用户',
  //     nickname: '公考新手',
  //     avatar: new URL('@/assets/avatar/user-avatar-default.svg', import.meta.url).href,
  //     email: 'visitor@example.com',
  //     phone: '13800138000',
  //     role: UserRole.USER,
  //     status: UserStatus.ACTIVE,
  //     gender: UserGender.MALE,
  //     birthday: '1990-01-01',
  //     location: 'beijing-haidian',
  //     bio: '正在努力备考公务员考试',
  //     lastLogin: now,
  //     registerIp: '127.0.0.1',
  //     preferences: {
  //       theme: 'light',
  //       language: 'zh-CN'
  //     },
  //     createdAt: now,
  //     updatedAt: now
  //   }
  // }

  const initUserState = () => {
    console.log('Initializing user state...')
    // 从本地存储恢复用户状态
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    console.log('Local storage data:', {
      savedToken: !!savedToken,
      savedUser: !!savedUser
    })
    
    if (savedToken && savedUser) {
      console.log('Token and user data found, restoring user state')
      token.value = savedToken
      try {
        user.value = JSON.parse(savedUser)
        console.log('User data parsed successfully')
        // 设置userId和user_id
        if (user.value) {
          localStorage.setItem('userId', user.value.id.toString())
          localStorage.setItem('user_id', user.value.id.toString())
        }
        // 验证token是否有效
        console.log('Fetching fresh user info to validate token')
        fetchUserInfo()
      } catch (e) {
        console.error('解析用户信息失败', e)
        // 清除无效数据
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        localStorage.removeItem('userId')
        localStorage.removeItem('user_id')
        user.value = null
        token.value = null
      }
    } else {
      console.log('No valid token or user data found, user is not authenticated')
      // 清除可能存在的无效数据
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('userId')
      localStorage.removeItem('user_id')
      user.value = null
      token.value = null
    }
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    error,
    // Getters
    isAuthenticated,
    isAdmin,
    // Actions
    login,
    register,
    fetchUserInfo,
    updateInfo,
    logout,
    clearError,
    setUser,
    setToken,
    initUserState
  }
})